<template>
  <div class="property-detail-page">
    <el-container>
      <el-header class="page-header">
        <el-button @click="$router.back()" icon="ArrowLeft" text>返回</el-button>
        <h2>房源详情</h2>
      </el-header>

      <el-main v-if="loading">
        <el-skeleton :rows="8" animated />
      </el-main>

      <el-main v-else-if="property">
        <el-row :gutter="24">
          <!-- 左侧图片区域 -->
          <el-col :span="16">
            <el-card class="image-card" shadow="never">
              <div class="image-gallery">
                <div class="main-image">
                  <img :src="currentImage" :alt="property.title" />
                  <div class="image-nav">
                    <el-button 
                      circle 
                      size="small" 
                      @click="prevImage" 
                      :disabled="currentImageIndex === 0"
                      icon="ArrowLeft"
                    />
                    <el-button 
                      circle 
                      size="small" 
                      @click="nextImage" 
                      :disabled="currentImageIndex === property.images.length - 1"
                      icon="ArrowRight"
                    />
                  </div>
                </div>
                <div class="thumbnails" v-if="property.images.length > 1">
                  <div 
                    v-for="(img, index) in property.images" 
                    :key="index"
                    class="thumbnail"
                    :class="{ active: index === currentImageIndex }"
                    @click="currentImageIndex = index"
                  >
                    <img :src="img" :alt="`图片${index + 1}`" />
                  </div>
                </div>
              </div>
            </el-card>

            <!-- 房源基本信息 -->
            <el-card class="info-card" shadow="never">
              <template #header>
                <div class="card-header">
                  <h3>{{ property.title }}</h3>
                  <div class="price-tag">
                    <span class="price">￥{{ property.price }}</span>
                    <span class="unit">/月</span>
                  </div>
                </div>
              </template>

              <div class="property-info">
                <div class="info-row">
                  <span class="label">房源类型：</span>
                  <span class="value">{{ getRoomTypeText(property.room_type) }}</span>
                </div>
                <div class="info-row">
                  <span class="label">房屋面积：</span>
                  <span class="value">{{ property.area }}㎡</span>
                </div>
                <div class="info-row">
                  <span class="label">房间配置：</span>
                  <span class="value">{{ property.bedrooms }}室{{ property.living_rooms }}厅{{ property.bathrooms }}卫</span>
                </div>
                <div class="info-row">
                  <span class="label">所在位置：</span>
                  <span class="value">{{ property.city }} {{ property.district }}</span>
                </div>
                <div class="info-row">
                  <span class="label">详细地址：</span>
                  <span class="value">{{ property.address }}</span>
                </div>
                <div class="info-row">
                  <span class="label">房源状态：</span>
                  <el-tag :type="getStatusType(property.status)">{{ getStatusText(property.status) }}</el-tag>
                </div>
              </div>

              <div class="description">
                <h4>房源描述</h4>
                <p>{{ property.description || '暂无描述' }}</p>
              </div>
            </el-card>
          </el-col>

          <!-- 右侧操作区域 -->
          <el-col :span="8">
            <el-card class="action-card" shadow="never">
              <div class="owner-info">
                <h4>房源信息</h4>
                <div class="owner-detail">
                  <div class="owner-item">
                    <span class="label">发布人：</span>
                    <span class="value">{{ property.owner_name || '未知' }}</span>
                  </div>
                  <div class="owner-item" v-if="property.owner_phone">
                    <span class="label">联系电话：</span>
                    <span class="value">{{ property.owner_phone }}</span>
                  </div>
                  <div class="owner-item">
                    <span class="label">发布时间：</span>
                    <span class="value">{{ formatDate(property.created_at) }}</span>
                  </div>
                </div>
              </div>

              <div class="action-buttons">
                <el-button type="primary" size="large" @click="showAppointmentDialog = true" :disabled="property.status !== 'available'">
                  <el-icon><Calendar /></el-icon>
                  预约看房
                </el-button>
                <el-button size="large" @click="showContactDialog = true">
                  <el-icon><Phone /></el-icon>
                  联系房东
                </el-button>
                <el-button size="large" @click="collectProperty">
                  <el-icon><Star /></el-icon>
                  {{ isCollected ? '已收藏' : '收藏' }}
                </el-button>
              </div>

              <div class="tips">
                <h4>温馨提示</h4>
                <ul>
                  <li>看房前请提前预约</li>
                  <li>实地看房时请注意安全</li>
                  <li>如有疑问可联系客服</li>
                </ul>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 评价区域 -->
        <el-card class="reviews-card" shadow="never" v-if="property">
          <template #header>
            <div class="reviews-header">
              <h3>用户评价</h3>
              <div class="rating-summary" v-if="reviewStats">
                <div class="rating-score">
                  <span class="score">{{ reviewStats.average_rating.toFixed(1) }}</span>
                  <div class="stars">
                    <el-rate :model-value="reviewStats.average_rating" disabled show-score />
                  </div>
                </div>
                <div class="rating-count">
                  <span>共{{ reviewStats.total_reviews }}条评价</span>
                </div>
              </div>
            </div>
          </template>

          <!-- 评价统计 -->
          <div class="rating-distribution" v-if="reviewStats && reviewStats.total_reviews > 0">
            <div class="distribution-item" v-for="(count, rating) in reviewStats.rating_distribution" :key="rating">
              <span class="rating-label">{{ rating }}星</span>
              <el-progress 
                :percentage="(count / reviewStats.total_reviews) * 100" 
                :show-text="false"
                :stroke-width="8"
              />
              <span class="rating-count">{{ count }}</span>
            </div>
          </div>

          <!-- 评价列表 -->
          <div class="reviews-list">
            <div class="review-item" v-for="review in reviews" :key="review.id">
              <div class="review-header">
                <div class="user-info">
                  <el-avatar :size="40" :src="review.user.avatar">
                    {{ review.user.username.charAt(0) }}
                  </el-avatar>
                  <div class="user-details">
                    <div class="username">{{ review.user.username }}</div>
                    <div class="rating">
                      <el-rate :model-value="review.rating" disabled size="small" />
                    </div>
                  </div>
                </div>
                <div class="review-date">{{ formatDate(review.created_at) }}</div>
              </div>
              <div class="review-content">
                <p>{{ review.content }}</p>
                <div class="review-images" v-if="review.images && review.images.length">
                  <img 
                    v-for="(img, index) in review.images" 
                    :key="index"
                    :src="img" 
                    :alt="`评价图片${index + 1}`"
                    class="review-image"
                    @click="previewImage(img)"
                  />
                </div>
              </div>
            </div>
          </div>

          <!-- 分页 -->
          <div class="reviews-pagination" v-if="reviewTotal > 0">
            <el-pagination
              v-model:current-page="reviewPage"
              :page-size="reviewPageSize"
              :total="reviewTotal"
              layout="prev, pager, next"
              @current-change="fetchReviews"
            />
          </div>

          <!-- 写评价按钮 -->
          <div class="write-review">
            <el-button type="primary" @click="showReviewDialog = true">
              <el-icon><Edit /></el-icon>
              写评价
            </el-button>
          </div>
        </el-card>
      </el-main>

      <el-main v-else>
        <el-empty description="房源不存在或已下架" />
      </el-main>
    </el-container>

    <!-- 预约看房对话框 -->
    <el-dialog v-model="showAppointmentDialog" title="预约看房" width="500px">
      <el-form :model="appointmentForm" label-width="80px">
        <el-form-item label="预约时间" required>
          <el-date-picker
            v-model="appointmentForm.date"
            type="datetime"
            placeholder="选择看房时间"
            style="width: 100%"
            :disabled-date="disabledDate"
          />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="appointmentForm.name" placeholder="请输入您的姓名" />
        </el-form-item>
        <el-form-item label="联系方式" required>
          <el-input v-model="appointmentForm.phone" placeholder="请输入您的手机号" />
        </el-form-item>
        <el-form-item label="备注信息">
          <el-input
            v-model="appointmentForm.remark"
            type="textarea"
            placeholder="请填写您的看房需求或特殊要求"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAppointmentDialog = false">取消</el-button>
        <el-button type="primary" @click="submitAppointment">提交预约</el-button>
      </template>
    </el-dialog>

    <!-- 联系房东对话框 -->
    <el-dialog v-model="showContactDialog" title="联系房东" width="400px">
      <div class="contact-info">
        <p><strong>房东姓名：</strong>{{ property?.owner_name || '未知' }}</p>
        <p v-if="property?.owner_phone"><strong>联系电话：</strong>{{ property.owner_phone }}</p>
        <p><strong>房源地址：</strong>{{ property?.address }}</p>
        <div class="contact-actions">
          <el-button type="primary" v-if="property?.owner_phone" @click="callPhone">
            <el-icon><Phone /></el-icon>
            拨打电话
          </el-button>
          <el-button @click="showContactDialog = false">关闭</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 写评价对话框 -->
    <el-dialog v-model="showReviewDialog" title="写评价" width="600px">
      <el-form :model="reviewForm" label-width="80px">
        <el-form-item label="评分">
          <el-rate v-model="reviewForm.rating" show-text />
        </el-form-item>
        <el-form-item label="评价内容">
          <el-input
            v-model="reviewForm.content"
            type="textarea"
            placeholder="请分享您的真实体验..."
            :rows="4"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="上传图片">
          <el-upload
            v-model:file-list="reviewForm.images"
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :limit="6"
            accept="image/*"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showReviewDialog = false">取消</el-button>
        <el-button type="primary" @click="submitReview">提交评价</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { propertiesAPI } from '@/api/properties'
import { reviewsAPI } from '@/api/reviews'
import { appointmentsAPI } from '@/api/appointments'
import { ElMessage } from 'element-plus'

const route = useRoute()
const property = ref(null)
const loading = ref(true)
const currentImageIndex = ref(0)
const showAppointmentDialog = ref(false)
const showContactDialog = ref(false)
const showReviewDialog = ref(false)
const isCollected = ref(false)

// 评价相关
const reviews = ref([])
const reviewStats = ref(null)
const reviewPage = ref(1)
const reviewPageSize = ref(10)
const reviewTotal = ref(0)

const appointmentForm = ref({
  date: '',
  phone: '',
  name: '',
  remark: ''
})

const reviewForm = ref({
  rating: 5,
  content: '',
  images: []
})

const currentImage = computed(() => {
  if (!property.value?.images?.length) {
    return 'https://picsum.photos/seed/house/800/600'
  }
  return property.value.images[currentImageIndex.value]
})

const getRoomTypeText = (type) => {
  const types = {
    apartment: '公寓',
    villa: '别墅',
    office: '写字楼',
    shop: '商铺'
  }
  return types[type] || '未知'
}

const getStatusText = (status) => {
  const statuses = {
    available: '可租',
    rented: '已租',
    sold: '已售',
    hidden: '已下架'
  }
  return statuses[status] || '未知'
}

const getStatusType = (status) => {
  const types = {
    available: 'success',
    rented: 'warning',
    sold: 'danger',
    hidden: 'info'
  }
  return types[status] || 'info'
}

const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

const prevImage = () => {
  if (currentImageIndex.value > 0) {
    currentImageIndex.value--
  }
}

const nextImage = () => {
  if (currentImageIndex.value < property.value.images.length - 1) {
    currentImageIndex.value++
  }
}

const collectProperty = () => {
  isCollected.value = !isCollected.value
  ElMessage.success(isCollected.value ? '收藏成功' : '取消收藏')
}

const submitAppointment = async () => {
  if (!appointmentForm.value.date || !appointmentForm.value.phone) {
    ElMessage.warning('请填写完整信息')
    return
  }

  try {
    const res = await appointmentsAPI.create({
      property_id: property.value.id,
      appointment_date: appointmentForm.value.date,
      contact_phone: appointmentForm.value.phone,
      contact_name: appointmentForm.value.name || '',
      remark: appointmentForm.value.remark || ''
    })

    if (res?.success) {
      ElMessage.success('预约提交成功，我们会尽快联系您')
      showAppointmentDialog.value = false
      appointmentForm.value = { date: '', phone: '', name: '', remark: '' }
    } else {
      ElMessage.error(res?.message || '预约提交失败')
    }
  } catch (error) {
    console.error('提交预约失败:', error)
    ElMessage.error('预约提交失败，请重试')
  }
}

const callPhone = () => {
  if (property.value?.owner_phone) {
    window.open(`tel:${property.value.owner_phone}`)
  }
}

// 评价相关方法
const fetchReviews = async () => {
  if (!property.value?.id) return
  
  try {
    const res = await reviewsAPI.list(property.value.id, {
      page: reviewPage.value,
      pageSize: reviewPageSize.value
    })
    if (res?.success) {
      reviews.value = res.data.items
      reviewTotal.value = res.data.total
    }
  } catch (error) {
    console.error('获取评价失败:', error)
  }
}

const fetchReviewStats = async () => {
  if (!property.value?.id) return
  
  try {
    const res = await reviewsAPI.stats(property.value.id)
    if (res?.success) {
      reviewStats.value = res.data
    }
  } catch (error) {
    console.error('获取评价统计失败:', error)
  }
}

const submitReview = async () => {
  if (!reviewForm.value.rating) {
    ElMessage.warning('请选择评分')
    return
  }
  
  try {
    const res = await reviewsAPI.create({
      property_id: property.value.id,
      rating: reviewForm.value.rating,
      content: reviewForm.value.content,
      images: reviewForm.value.images.map(img => img.url || img.response?.url)
    })
    
    if (res?.success) {
      ElMessage.success('评价提交成功，等待审核')
      showReviewDialog.value = false
      reviewForm.value = { rating: 5, content: '', images: [] }
      fetchReviews()
      fetchReviewStats()
    }
  } catch (error) {
    ElMessage.error('提交评价失败')
  }
}

const previewImage = (url) => {
  // 简单的图片预览
  window.open(url, '_blank')
}

const disabledDate = (time) => {
  // 禁用过去的日期
  return time.getTime() < Date.now() - 8.64e7
}

const fetchPropertyDetail = async () => {
  try {
    loading.value = true
    const id = route.params.id || route.query.id
    if (!id) {
      ElMessage.error('房源ID不存在')
      return
    }
    
    const res = await propertiesAPI.detail(id)
    if (res?.success) {
      property.value = res.data
    } else {
      ElMessage.error('获取房源详情失败')
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后重试')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchPropertyDetail()
})

// 监听房源数据变化，加载评价
watch(() => property.value?.id, (newId) => {
  if (newId) {
    fetchReviews()
    fetchReviewStats()
  }
})
</script>

<style scoped>
.property-detail-page {
  min-height: 100vh;
  background: #f6f8fb;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 16px;
  height: 72px;
  background: #fff;
  border-bottom: 1px solid #e8e8e8;
}

.image-card, .info-card, .action-card {
  margin-bottom: 16px;
  border-radius: 8px;
}

.image-gallery {
  position: relative;
}

.main-image {
  position: relative;
  width: 100%;
  height: 400px;
  border-radius: 8px;
  overflow: hidden;
}

.main-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-nav {
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
  padding: 0 16px;
  transform: translateY(-50%);
}

.thumbnails {
  display: flex;
  gap: 8px;
  margin-top: 12px;
  overflow-x: auto;
}

.thumbnail {
  flex-shrink: 0;
  width: 80px;
  height: 60px;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  border: 2px solid transparent;
  transition: border-color 0.3s;
}

.thumbnail.active {
  border-color: #409eff;
}

.thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price-tag {
  text-align: right;
}

.price {
  font-size: 24px;
  font-weight: bold;
  color: #ff4d4f;
}

.unit {
  font-size: 14px;
  color: #8c8c8c;
  margin-left: 4px;
}

.property-info {
  margin-bottom: 24px;
}

.info-row {
  display: flex;
  margin-bottom: 12px;
  align-items: center;
}

.label {
  width: 100px;
  color: #8c8c8c;
  font-size: 14px;
}

.value {
  flex: 1;
  color: #333;
  font-size: 14px;
}

.description h4 {
  margin-bottom: 12px;
  color: #333;
}

.description p {
  line-height: 1.6;
  color: #666;
}

.owner-info {
  margin-bottom: 24px;
}

.owner-info h4 {
  margin-bottom: 16px;
  color: #333;
}

.owner-detail {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 6px;
}

.owner-item {
  display: flex;
  margin-bottom: 8px;
  align-items: center;
}

.owner-item .label {
  width: 80px;
  color: #8c8c8c;
  font-size: 13px;
}

.owner-item .value {
  flex: 1;
  color: #333;
  font-size: 13px;
}

.action-buttons {
  margin-bottom: 24px;
}

.action-buttons .el-button {
  width: 100%;
  margin-bottom: 12px;
}

.tips {
  background: #f0f9ff;
  padding: 16px;
  border-radius: 6px;
  border-left: 4px solid #409eff;
}

.tips h4 {
  margin-bottom: 12px;
  color: #333;
  font-size: 14px;
}

.tips ul {
  margin: 0;
  padding-left: 16px;
}

.tips li {
  color: #666;
  font-size: 13px;
  line-height: 1.5;
  margin-bottom: 4px;
}

.contact-info {
  padding: 16px 0;
}

.contact-info p {
  margin-bottom: 12px;
  color: #333;
}

.contact-actions {
  margin-top: 20px;
  text-align: center;
}

/* 评价相关样式 */
.reviews-card {
  margin-top: 24px;
}

.reviews-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.rating-summary {
  display: flex;
  align-items: center;
  gap: 16px;
}

.rating-score {
  display: flex;
  align-items: center;
  gap: 8px;
}

.score {
  font-size: 24px;
  font-weight: bold;
  color: #ff4d4f;
}

.rating-count {
  color: #8c8c8c;
  font-size: 14px;
}

.rating-distribution {
  margin: 16px 0;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.distribution-item {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.distribution-item:last-child {
  margin-bottom: 0;
}

.rating-label {
  width: 40px;
  font-size: 12px;
  color: #8c8c8c;
}

.rating-count {
  width: 30px;
  text-align: right;
  font-size: 12px;
  color: #8c8c8c;
}

.reviews-list {
  margin: 16px 0;
}

.review-item {
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.review-item:last-child {
  border-bottom: none;
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.username {
  font-weight: 500;
  color: #333;
}

.review-date {
  color: #8c8c8c;
  font-size: 12px;
}

.review-content p {
  margin: 0 0 12px 0;
  line-height: 1.6;
  color: #333;
}

.review-images {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.review-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  transition: transform 0.2s;
}

.review-image:hover {
  transform: scale(1.05);
}

.reviews-pagination {
  display: flex;
  justify-content: center;
  margin: 16px 0;
}

.write-review {
  text-align: center;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}
</style>
